<template>
  <view class="layout">
    <wd-navbar
      title="登录"
      placeholder
      left-arrow
      :style="{ marginTop: `${navHeight}px` }"
    />
    <view class="content">
      <wd-form ref="form" :model="loginInfo">
        <wd-cell-group border>
          <view class="title"> 手机号 </view>
          <wd-input
            v-model="loginInfo.phone"
            label-width="80px"
            prop="phone"
            clearable
            custom-label-class="custom-label-class"
            placeholder="请填写手机号"
            :rules="[{ required: true, message: '手机号不能为空' }]"
          />
          <view class="title mt-20"> 密码 </view>
          <wd-input
            v-model="loginInfo.password"
            label-width="80px"
            type="number"
            prop="password"
            custom-label-class="custom-label-class"
            clearable
            show-password
            placeholder="请填写密码"
            :rules="[{ required: true, message: '密码不能为空' }]"
          />
        </wd-cell-group>
      </wd-form>
    </view>
    <view class="flex-center">
      <wd-button
        type="primary"
        size="large"
        block
        :align-right="false"
        class="confirm"
        @click="handleSubmit"
      >
        登录
      </wd-button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import CryptoJS from "crypto-js";
import LoginApi from "@/api/login";
import TeacherApi from "@/api/teacher";
import sha256 from "@/libs/sha256";
import { useConfigStore } from "@/store/config";
import { useTokenStore } from "@/store/token";
import { useUserStore } from "@/store/user";
import { tabbarList } from "@/tabbar/config";
import { isPageTabbar } from "@/tabbar/store";
import { ensureDecodeURIComponent } from "@/utils";
import { parseUrlToObj } from "@/utils/index";

definePage({
  style: {
    navigationBarTitleText: "登录",
    navigationStyle: "custom",
  },
});
const configStore = useConfigStore();
const navHeight = ref(0);
navHeight.value = configStore.systemBarHeight;

const form = ref();

const loginInfo = reactive<{
  phone: string;
  password: string;
}>({
  phone: "",
  password: "",
});

const redirectUrl = ref("");
onLoad((options) => {
  console.log("login options: ", options);
  if (options.redirect) {
    redirectUrl.value = ensureDecodeURIComponent(options.redirect);
  } else {
    redirectUrl.value = tabbarList[0].pagePath;
  }
  console.log("redirectUrl.value: ", redirectUrl.value);
});

const userStore = useUserStore();
const tokenStore = useTokenStore();
async function doLogin() {
  if (tokenStore.hasLogin) {
    uni.navigateBack();
    return;
  }
  try {
    // 调用登录接口
    await tokenStore.login({
      username: "菲鸽",
      password: "123456",
    });
    console.log(redirectUrl.value);
  } catch (error) {
    console.log("登录失败", error);
  }
  let path = redirectUrl.value;
  if (!path.startsWith("/")) {
    path = `/${path}`;
  }
  const { path: _path, query } = parseUrlToObj(path);
  console.log("_path:", _path, "query:", query, "path:", path);
  console.log("isPageTabbar(_path):", isPageTabbar(_path));
  if (isPageTabbar(_path)) {
    // 经过我的测试 switchTab 不能带 query 参数, 不管是放到 url  还是放到 query ,
    // 最后跳转过去的时候都会丢失 query 信息
    uni.switchTab({
      url: path,
    });
    // uni.switchTab({
    //   url: _path,
    //   query,
    // })
  } else {
    // 自己决定是 redirectTo 还是 navigateBack
    // uni.redirectTo({
    //   url: path,
    // })
    uni.navigateBack();
  }
}

function handleSubmit() {
  form.value.validate().then(async ({ valid, errors }) => {
    if (valid) {
      const params = {
        account: loginInfo.phone,
        password: sha256.sha256_digest(loginInfo.password),
        osver: "weixin",
      };
      const res = await LoginApi.login(params);
      if (res) {
        userStore.userInfo.userId = res?.uid;
        userStore.userInfo.fullName = res?.fullName;
        const bindres = await TeacherApi.bindTeacher({
          uid: res?.uid,
        });
        console.log("bindres:", bindres);
        console.log("userStore.userInfo.userId:", userStore.userInfo.userId);

        console.log("登录成功", res);
        uni.switchTab({ url: "/pages/index/index" });
      }
    }
  });
}
</script>

<style lang="scss" scoped>
.layout {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  position: relative;
  .content {
    margin: 40px 25px;
    width: calc(100% - 50px);
  }
}
.flex-center {
  width: 100%;
  display: flex;
  justify-content: center;
  align-content: center;
  position: absolute;
  top: 70%;
  .confirm {
    width: 80%;
    border-radius: 10px;
  }
}
.title {
  font-size: 12px;
  font-weight: normal;
  line-height: normal;
  letter-spacing: 0em;
  color: #333333;
}
</style>
